package handlers

import (
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"

	"webcppcluster/account"
	"webcppcluster/cache"
	"webcppcluster/config"
	"webcppcluster/lobby"
	"webcppcluster/shop"
	"webcppcluster/task"
	"webcppcluster/utils"
)

var redisStore *cache.RedisStore

func Init(store *cache.RedisStore) {
	redisStore = store
}

// Hello 测试接口
func Hello(c *gin.Context) {
	c.String(http.StatusOK, "Hello, World!")
}

// Register 注册
func Register(c *gin.Context) {
	phonenum := c.PostForm("phonenum")
	password := c.PostForm("password")
	nick := c.PostForm("nick")
	sex := c.PostForm("sex")
	idcard := c.PostForm("idcard")

	// 检测手机号格式
	if !account.CheckPhonenum(phonenum) {
		c.Data(http.StatusOK, "application/json", utils.ErrResult(
			config.ECRegisterPhonenumTypeError,
			config.GetErrorMessage(config.ECRegisterPhonenumTypeError)))
		return
	}

	// 检测密码格式
	if !account.CheckPassword(password) {
		c.Data(http.StatusOK, "application/json", utils.ErrResult(
			config.ECRegisterPasswordTypeError,
			config.GetErrorMessage(config.ECRegisterPasswordTypeError)))
		return
	}

	// 检测账号是否重复
	notRepeat, err := account.CheckUserIdNotRepeat(phonenum)
	if err != nil {
		utils.LogError(err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "服务器错误"})
		return
	}
	if !notRepeat {
		c.Data(http.StatusOK, "application/json", utils.ErrResult(
			config.ECRegisterUseridRepeat,
			config.GetErrorMessage(config.ECRegisterUseridRepeat)))
		return
	}

	// 注册账号
	if err := account.InitUser(phonenum, password, nick, sex, idcard, redisStore); err != nil {
		utils.LogError(err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "注册失败"})
		return
	}

	c.Data(http.StatusOK, "application/json", utils.SuccessResult(map[string]interface{}{
		"code": config.ECReqNormal,
	}))
}

// Login 登录
func Login(c *gin.Context) {
	userid := c.PostForm("userid")
	password := c.PostForm("password")

	code, reason := account.VerifyAccount(userid, password)
	if code != config.ECReqNormal {
		c.Data(http.StatusOK, "application/json", utils.ErrResult(code, reason))
		return
	}

	// 处理登录成功
	code, reason = account.HandleLogin(userid, redisStore)
	if code != config.ECReqNormal {
		c.Data(http.StatusOK, "application/json", utils.ErrResult(code, reason))
		return
	}

	// 设置session
	session := sessions.Default(c)
	session.Set("userid", userid)
	if err := session.Save(); err != nil {
		utils.LogError(err)
	}

	c.Data(http.StatusOK, "application/json", utils.SuccessResult(map[string]interface{}{
		"code": config.ECReqNormal,
	}))
}

// CheckLoginMiddleware 登录检查中间件
func CheckLoginMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		userid := session.Get("userid")
		if userid == nil {
			c.Data(http.StatusOK, "application/json", utils.ErrResult(
				config.ECLoginInvalid,
				config.GetErrorMessage(config.ECLoginInvalid)))
			c.Abort()
			return
		}
		c.Set("userid", userid)
		c.Next()
	}
}

// Shopcfg 获取商城配置
func Shopcfg(c *gin.Context) {
	versionStr := c.Query("version")
	version, _ := strconv.Atoi(versionStr)
	
	shopcfg := shop.GetShopCfg(version)
	c.Data(http.StatusOK, "application/json", utils.SuccessResult(shopcfg))
}

// Shopbuy 购买道具
func Shopbuy(c *gin.Context) {
	useridStr := c.PostForm("userid")
	propidStr := c.PostForm("propid")
	propnumStr := c.PostForm("propnum")
	shopversionStr := c.PostForm("shopversion")
	versionStr := c.PostForm("version")
	paytypeStr := c.PostForm("paytype")

	userid, _ := strconv.Atoi(useridStr)
	propid, _ := strconv.Atoi(propidStr)
	propnum, _ := strconv.Atoi(propnumStr)
	shopversion, _ := strconv.Atoi(shopversionStr)
	version, _ := strconv.Atoi(versionStr)
	paytype, _ := strconv.Atoi(paytypeStr)

	code, data := shop.ShopBuy(userid, propid, propnum, shopversion, version, paytype, redisStore)
	if code != config.ECReqNormal {
		c.Data(http.StatusOK, "application/json", utils.ErrResult(code, config.GetErrorMessage(code)))
		return
	}

	c.Data(http.StatusOK, "application/json", utils.SuccessResult(data))
}

// Taskcfg 获取任务配置
func Taskcfg(c *gin.Context) {
	useridStr := c.Query("userid")
	versionStr := c.Query("version")

	userid, _ := strconv.ParseInt(useridStr, 10, 64)
	version, _ := strconv.Atoi(versionStr)

	taskcfg := task.GetTaskCfg(userid, version, redisStore)
	c.Data(http.StatusOK, "application/json", utils.SuccessResult(map[string]interface{}{
		"taskcfg": taskcfg,
	}))
}

// Taskreward 领取任务奖励
func Taskreward(c *gin.Context) {
	// TODO: 实现领取奖励逻辑
	c.Data(http.StatusOK, "application/json", utils.SuccessResult(map[string]interface{}{
		"code": config.ECReqNormal,
	}))
}

// Sign 签到
func Sign(c *gin.Context) {
	useridStr := c.PostForm("userid")
	signtypeStr := c.PostForm("signtype")
	date := c.PostForm("date")

	userid, _ := strconv.ParseInt(useridStr, 10, 64)
	signtype, _ := strconv.Atoi(signtypeStr)
	if signtype == 0 {
		signtype = config.SignTypeToday
	}

	if err := task.UserSign(userid, signtype, date, redisStore); err != nil {
		utils.LogError(err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "签到失败"})
		return
	}

	c.Data(http.StatusOK, "application/json", utils.SuccessResult(map[string]interface{}{
		"code": config.ECReqNormal,
	}))
}

// Mailsend 发送邮件
func Mailsend(c *gin.Context) {
	useridlist := c.PostForm("useridlist")
	title := c.PostForm("title")
	context := c.PostForm("context")
	typeStr := c.PostForm("type")
	attach := c.PostForm("attach")
	isglobal := c.PostForm("isglobal")
	fromuseridStr := c.PostForm("fromuserid")
	buttontext := c.PostForm("buttontext")

	// 解析参数
	useridlistArr := []string{}
	if useridlist != "" {
		// 简单的分割，实际可能需要更复杂的解析
		for _, id := range splitByComma(useridlist) {
			useridlistArr = append(useridlistArr, id)
		}
	}

	mailType, _ := strconv.Atoi(typeStr)
	fromuserid, _ := strconv.ParseInt(fromuseridStr, 10, 64)
	isglobalInt, _ := strconv.Atoi(isglobal)

	// 解析attach JSON
	attachMap := make(map[string]interface{})
	if attach != "" {
		json.Unmarshal([]byte(attach), &attachMap)
	}

	mailinfo := map[string]interface{}{
		"useridlist": useridlistArr,
		"title":      title,
		"context":    context,
		"type":       mailType,
		"attach":     attachMap,
		"isglobal":   isglobalInt,
		"fromuserid": fromuserid,
		"buttontext": buttontext,
	}

	if err := lobby.SendMail(mailinfo, redisStore); err != nil {
		utils.LogError(err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "发送邮件失败"})
		return
	}

	c.Data(http.StatusOK, "application/json", utils.SuccessResult(map[string]interface{}{
		"code": config.ECReqNormal,
	}))
}

// Maillist 获取邮件列表
func Maillist(c *gin.Context) {
	useridStr := c.Query("userid")
	userid, _ := strconv.ParseInt(useridStr, 10, 64)

	mailinfolist := lobby.GetMailList(userid, redisStore)
	c.Data(http.StatusOK, "application/json", utils.SuccessResult(map[string]interface{}{
		"mailinfolist": mailinfolist,
	}))
}

// splitByComma 按逗号分割字符串
func splitByComma(s string) []string {
	result := []string{}
	current := ""
	for _, char := range s {
		if char == ',' {
			if current != "" {
				result = append(result, current)
				current = ""
			}
		} else {
			current += string(char)
		}
	}
	if current != "" {
		result = append(result, current)
	}
	return result
}

